package com.socool.sinofaith.ui;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.deying.actionbarcompat.ActionBarActivity;
import com.deying.actionbarcompat.ActionBarHelperBase;
import com.deying.actionbarcompat.ActionBarHelperBase.CenterViewFactory;
import com.deying.actionbarcompat.ActionBarHelperBase.SpinnerViewFactory;
import com.socool.sinofaith.R;
import com.socool.sinofaith.SocoolApplication;
import com.socool.sinofaith.dao.QuestionAnswerDao;
import com.socool.sinofaith.dao.SifQuestionOptionsDao;
import com.socool.sinofaith.dao.SifTaskDao;
import com.socool.sinofaith.dao.SifTaskQuestionDao;
import com.socool.sinofaith.jsonparse.HttpJsonAdapter;
import com.socool.sinofaith.model.AnswerReq;
import com.socool.sinofaith.model.QuestionAnswerBean;
import com.socool.sinofaith.model.QuestionAnswerReqBean;
import com.socool.sinofaith.model.SifQuestionOptionsBean;
import com.socool.sinofaith.model.SifTaskBean;
import com.socool.sinofaith.model.SifTaskQuestionBean;
import com.socool.sinofaith.model.ViewQuestionBean;
import com.socool.sinofaith.model.ViewQuestionBean.Question;
import com.socool.sinofaith.model.ViewQuestionBean.Question.Option;
import com.socool.sinofaith.util.ConstansJsonUrl;
import com.socool.sinofaith.util.S;
import com.socool.sinofaith.util.SinofaithUtil;
import com.socool.sinofaith.view.LoadingDialog;
import com.socool.sinofaith.view.MyDialog;
import com.socool.sinofaith.view.MyGridView;

import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
/**
 * 答题
 * @author jiang
 *
 */
public class AnswerQuestionActivity extends ActionBarActivity
		implements CenterViewFactory, SpinnerViewFactory, View.OnClickListener {
	ActionBarHelperBase mActionBarHelperBase;

	private LinearLayout linearLayout;
	private boolean isFirstDo;

	private TextView questionName;

	private TextView tv, tv_progress;

	private String userMobile;
	private String questionStr = "";

	private Button btnPrevious, btnNext;

	private SifTaskQuestionBean taskQuestionBean;
	private ArrayList<SifTaskQuestionBean> questionBeans;
	private SifQuestionOptionsBean questionOptionsBean;
	private ArrayList<SifQuestionOptionsBean> Optionsbeans;
	private SifTaskBean taskBean;
	List<SifTaskBean> tasklist;
	SifTaskDao taskDao;

	private Map<String, String> map;

	private String temp, Template_ID, Task_Name, taskid, SubTask_ID, Stemp_ID, imgtemp, previousQid, type, Answer_ID,
			flag, autoflag, batchflag, taskName, taskQuestionID, jumpTo = "";
	private Button button;
	private int count;
	int PhotoNum = 0;

	private int REQUEST_CODE_PICK_IMAGE = 100;
	private int REQUEST_CODE_CAPTURE_CAMEIA = 200;
	private int REQUEST_CODE_AUDIO = 400;
	private int REQUEST_CODE_VIDEO = 500;
	protected static final int REQCAMERA = 11;
	private ContentResolver mContentResolver;
	final int IMAGE_MAX_SIZE = 1024;

	private QuestionAnswerReqBean answerReqBean;
	private ArrayList<AnswerReq> SubAnswer;

	private boolean otherflag = false;

	ArrayList<SifQuestionOptionsBean> newOptionsbeans = new ArrayList<SifQuestionOptionsBean>();

	private int currentPosition = 1;// 本地答题顺便
	private HashMap<Integer, Integer> previousHaspMap = new HashMap<Integer, Integer>(); // 存储当前位置的上一题位置
	private QuestionAnswerBean previousAnswerBean;

	MyGridView gridView;
	String PhotoMode;
	ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();

	private LoadingDialog mLoadingDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_answerquestion);
		SocoolApplication.addActivity(this);
		mActionBarHelperBase = (ActionBarHelperBase) this.getActionBarHelper();
		mActionBarHelperBase.setmCenterViewFactory(this);
		mActionBarHelperBase.setmSpinnerViewFactory(this);
		mActionBarHelperBase.setmClickListener(this);
		userMobile = getSPString();
		taskDao = new SifTaskDao(this);
		gridView = new MyGridView(this, null);

		if (null != savedInstanceState && null != savedInstanceState.getSerializable("taskQuestionBean")) {
			taskQuestionBean = (SifTaskQuestionBean) savedInstanceState.getSerializable("taskQuestionBean");

			map = new HashMap<String, String>();
			Set<String> keySet = savedInstanceState.getBundle("map").keySet();
			Iterator<String> iter = keySet.iterator();
			while (iter.hasNext()) {
				String key = iter.next();
				map.put(key, String.valueOf(savedInstanceState.getBundle("map").get(key)));
			}
			taskBean = (SifTaskBean) savedInstanceState.getSerializable("taskBean");
			init();
			if ("1".equals(taskBean.getGoBackSet()) && !"1".equals(taskQuestionBean.getOrderIndex())) {
				btnPrevious.setVisibility(View.VISIBLE);
			} else {
				btnPrevious.setVisibility(View.GONE);
			}

			lstImageItem = (ArrayList<HashMap<String, Object>>) savedInstanceState.getSerializable("list");

			PhotoMode = savedInstanceState.getString("PhotoMode");
			PhotoNum = savedInstanceState.getInt("PhotoNum");
		}

		init();

		getQuestions();
	}

	void init() {
		mLoadingDialog = new LoadingDialog(AnswerQuestionActivity.this);
		mContentResolver = getContentResolver();
		tv = new TextView(this);

		linearLayout = (LinearLayout) findViewById(R.id.prarms_layout);

		questionName = (TextView) findViewById(R.id.questionName);

		btnPrevious = (Button) findViewById(R.id.btnPrevious);
		btnNext = (Button) findViewById(R.id.btnNext);

		tv_progress = (TextView) findViewById(R.id.tv_progress);

		btnPrevious.setOnClickListener(this);
		btnNext.setOnClickListener(this);

		Task_Name = "问卷回答";

		Template_ID = getIntent().getStringExtra("Template_ID");
		taskid = this.getIntent().getStringExtra("taskid");
		SubTask_ID = getIntent().getStringExtra("subtaskid");
		Stemp_ID = getIntent().getStringExtra("Stemp_ID");
		type = getIntent().getStringExtra("type");
		flag = getIntent().getStringExtra("flag");
		autoflag = getIntent().getStringExtra("autoflag");
		batchflag = getIntent().getStringExtra("batchflag");
		taskName = getIntent().getStringExtra("taskName");

		answerReqBean = new QuestionAnswerReqBean();
		answerReqBean.setTask_ID(taskid);
		answerReqBean.setSubTask_ID(SubTask_ID);
		answerReqBean.setStemp_ID(null == Stemp_ID ? "" : Stemp_ID);
		answerReqBean.setSubmiter(userMobile);
		SubAnswer = new ArrayList<AnswerReq>();
		if ("1".equals(type) || "".equals(type) || null == type) {

			tasklist = taskDao.queryBySql("select * from " + SifTaskBean.TABLENAME + " where Task_ID='" + taskid + "'");
			Task_Name = "问卷回答";
			if (null != tasklist && tasklist.size() > 0) {
				taskBean = tasklist.get(0);
				Task_Name = taskBean.getTaskName();
			}
		} else {
			Answer_ID = getIntent().getStringExtra("Answer_ID");
		}
		if (null != taskName && !"".equals(taskName)) {
			Task_Name = taskName;
		}

		if (null == lstImageItem || lstImageItem.size() <= 0) {
			lstImageItem = new ArrayList<HashMap<String, Object>>();
		} else {
			SimpleAdapter saImageItems = new SimpleAdapter(this, // 没什么解释
					lstImageItem, // 数据来源
					R.layout.night_item, // night_item的XML实现
					// 动态数组与ImageItem对应的子项
					new String[] { "ItemImage", "ItemText" }, new int[] { R.id.ItemImage, R.id.ItemText });
			gridView.setAdapter(saImageItems);
			saImageItems.notifyDataSetChanged();
			// gridView.setOnItemClickListener(new ItemClickListener());
		}
		isFirstAnswer();
	}

	void getQuestions() {
		if ("1".equals(type) || "".equals(type) || null == type) {
			new AsyncTask<Void, Void, ArrayList<SifTaskQuestionBean>>() {

				@Override
				protected ArrayList<SifTaskQuestionBean> doInBackground(Void... arg0) {
					SifTaskQuestionDao taskQuestionDao = new SifTaskQuestionDao(AnswerQuestionActivity.this);
					questionBeans = taskQuestionDao.queryBySql(
							"select * from " + SifTaskQuestionBean.TABLENAME + " where Template_ID='" + Template_ID
									+ "' and Task_ID='" + taskid + "'" + " order by cast(OrderIndex as INTEGER)");
					if (questionBeans.size() > 0 && questionBeans.get(0).getOrderIndex().equals("0")) {
						for (int i = 0; i < questionBeans.size(); i++) {
							questionBeans.get(i).setOrderIndex((i + 1) + "");
						}
					}

					return questionBeans;
				}

				@Override
				protected void onPostExecute(ArrayList<SifTaskQuestionBean> result) {
					// TODO Auto-generated method stub
					super.onPostExecute(result);
					if (result != null && result.size() > 0) {
						if ("2".equals(flag)) {
							QuestionAnswerDao answerDao = new QuestionAnswerDao(AnswerQuestionActivity.this);
							String sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid
									+ " and SubTask_ID=" + SubTask_ID;
							if (null != Stemp_ID && !"".equals(Stemp_ID)) {
								sql += " and Stemp_ID=" + Stemp_ID;
							}
							sql += " and Submiter=" + userMobile;
							ArrayList<QuestionAnswerBean> answerBeans = answerDao.queryBySql(sql);
							QuestionAnswerBean firstAnswerBean = new QuestionAnswerBean();
							if (null != answerBeans && answerBeans.size() > 0) {
								firstAnswerBean = answerBeans.get(answerBeans.size() - 1);
								for (int i = 0; i < result.size(); i++) {
									taskQuestionBean = result.get(i);
									if (taskQuestionBean.getTaskQuestion_ID()
											.equals(firstAnswerBean.getTaskQuestion_ID())) {
										break;
									}
								}
								for (int k = 0; k < answerBeans.size(); k++) {
									QuestionAnswerBean bean = answerBeans.get(k);
									currentPosition++;
									String Formto = "1";
									if (null != bean.getFormto() && !"null".equals(bean.getFormto())) {
										Formto = bean.getFormto();
									}
									previousHaspMap.put(currentPosition, Integer.valueOf(Formto));
								}

							} else {
								int orderindex = 0;
								if (null != taskQuestionBean && !"".equals(taskQuestionBean.getOrderIndex())) {
									orderindex = Integer.valueOf(taskQuestionBean.getOrderIndex());
								}
								taskQuestionBean = result.get(orderindex);
							}
						} else {
							int orderindex = 0;
							if (null != taskQuestionBean && !"".equals(taskQuestionBean.getOrderIndex())) {
								orderindex = Integer.valueOf(taskQuestionBean.getOrderIndex());
							}
							taskQuestionBean = result.get(orderindex);
						}
						// int orderindex = 0;
						// if (null != taskQuestionBean
						// && !"".equals(taskQuestionBean
						// .getOrderIndex())) {
						// orderindex = Integer.valueOf(taskQuestionBean
						// .getOrderIndex());
						// }
						// taskQuestionBean = result.get(orderindex);
						getOptions(taskQuestionBean.getTaskQuestion_ID());
					}
				}
			}.execute();
		} else {
			new AsyncTask<Void, Void, ArrayList<SifTaskQuestionBean>>() {

				@Override
				protected ArrayList<SifTaskQuestionBean> doInBackground(Void... arg0) {
					SifTaskQuestionDao taskQuestionDao = new SifTaskQuestionDao(AnswerQuestionActivity.this);
					questionBeans = taskQuestionDao
							.queryBySql("select * from " + SifTaskQuestionBean.TABLENAME + " where Task_ID='" + taskid
									+ "' and Template_ID='" + Template_ID + "' order by cast(OrderIndex as INTEGER)");
					return questionBeans;
				}

				@Override
				protected void onPostExecute(ArrayList<SifTaskQuestionBean> result) {
					// TODO Auto-generated method stub
					super.onPostExecute(result);
					if (result != null && result.size() > 0) {

						int orderindex = 0;
						if (null != taskQuestionBean && !"".equals(taskQuestionBean.getOrderIndex())) {
							orderindex = Integer.valueOf(taskQuestionBean.getOrderIndex());
						}
						taskQuestionBean = result.get(orderindex);
						getOptions(taskQuestionBean.getTaskQuestion_ID());
					} else {
						getNetData();
					}
				}
			}.execute();
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	void getNetData() {
		FinalHttp fh = new FinalHttp();
		AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.viewQuestion_url);
		params.put("did", SinofaithUtil.did);
		params.put("answerid", Answer_ID);
		Log.v("qqqq", ConstansJsonUrl.REQUEST_URL + params);
		fh.get(ConstansJsonUrl.REQUEST_URL, params, new AjaxCallBack() {

			@Override
			public void onStart() {
				super.onStart();
			}

			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				super.onLoading(count, current);
			}

			@Override
			public void onSuccess(Object t) {
				// TODO Auto-generated method stub
				super.onSuccess(t);
				Log.v("qqqq", t.toString());
				try {
					ViewQuestionBean viewQuestionBean = HttpJsonAdapter.getInstance().get(t.toString(),
							ViewQuestionBean.class);
					if (viewQuestionBean.getResult().equals("0")) {

						if (null != viewQuestionBean.getQuestionList()
								&& viewQuestionBean.getQuestionList().size() > 0) {

							ArrayList<Question> questions = viewQuestionBean.getQuestionList();
							questionBeans = new ArrayList<SifTaskQuestionBean>();
							Optionsbeans = new ArrayList<SifQuestionOptionsBean>();
							if (null != questions && questions.size() > 0) {
								for (int i = 0; i < questions.size(); i++) {
									Question question = questions.get(i);
									taskQuestionBean = new SifTaskQuestionBean();
									taskQuestionBean.setTaskQuestion_ID(question.getTaskQuestion_ID());
									taskQuestionBean.setTemplate_ID(question.getTemplate_ID());
									taskQuestionBean.setQuestion(question.getQuestion());
									taskQuestionBean.setQuestionType(question.getQuestionType());
									taskQuestionBean.setHasOtherOption(question.getHasOtherOption());
									taskQuestionBean.setOrderIndex(question.getOrderIndex());
									taskQuestionBean.setIsRequired(question.getIsRequired());
									taskQuestionBean.setPhotoNum(question.getPhotoNum());
									taskQuestionBean.setPhotoMode(question.getPhotoMode());
									taskQuestionBean.setPhotoDesc(question.getPhotoDesc());
									taskQuestionBean.setZaikuFlag(question.getZaikuFlag());
									questionBeans.add(taskQuestionBean);

									ArrayList<Option> options = question.getOptionList();
									if (null != options && options.size() > 0) {
										for (int k = 0; k < options.size(); k++) {
											Option option = options.get(k);
											questionOptionsBean = new SifQuestionOptionsBean();
											questionOptionsBean.setOP_ID(option.getOP_ID());
											questionOptionsBean.setTaskQuestion_ID(option.getTaskQuestion_ID());
											questionOptionsBean.setOptionValue(option.getOptionValue());
											questionOptionsBean.setIsDefault(option.getIsDefault());
											questionOptionsBean.setJumpTo(option.getJumpTo());
											Optionsbeans.add(questionOptionsBean);
										}
									}
								}
							}
							newOptionsbeans = Optionsbeans;
							int orderindex = 0;
							taskQuestionBean = questionBeans.get(orderindex);
							// getOptions(taskQuestionBean.getTaskQuestion_ID());

							tasklist = taskDao.queryBySql("select * from " + SifTaskBean.TABLENAME + " where Task_ID='"
									+ viewQuestionBean.getTaskid() + "'");
							if (null != tasklist && tasklist.size() > 0) {
								taskBean = tasklist.get(0);
								Task_Name = taskBean.getTaskName();
								tv.setText(Task_Name);
							}

							answerReqBean.setTask_ID(viewQuestionBean.getTaskid());
							answerReqBean.setSubTask_ID(SubTask_ID);
							answerReqBean.setStemp_ID(null == Stemp_ID ? "" : Stemp_ID);

							getOptions(taskQuestionBean.getTaskQuestion_ID());
						}

					} else {
						Toast.makeText(AnswerQuestionActivity.this, viewQuestionBean.getDesc(), Toast.LENGTH_LONG)
								.show();
						AnswerQuestionActivity.this.finish();
					}
				} catch (Exception e) {
					Toast.makeText(AnswerQuestionActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
					AnswerQuestionActivity.this.finish();
				}

			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				// TODO Auto-generated method stub
				super.onFailure(t, errorNo, strMsg);
				Toast.makeText(AnswerQuestionActivity.this, strMsg, Toast.LENGTH_LONG).show();
			}

		});
	}

	void getOptions(final String TaskQuestion_ID) {
		if ("1".equals(type) || "".equals(type) || null == type) {
			new AsyncTask<Void, Void, ArrayList<SifQuestionOptionsBean>>() {

				@Override
				protected ArrayList<SifQuestionOptionsBean> doInBackground(Void... arg0) {
					SifQuestionOptionsDao questionOptionsDao = new SifQuestionOptionsDao(AnswerQuestionActivity.this);
					Optionsbeans = questionOptionsDao.queryBySql("select * from " + SifQuestionOptionsBean.TABLENAME
							+ " where TaskQuestion_ID='" + TaskQuestion_ID + "' and Task_ID=" + taskid);
					return Optionsbeans;
				}

				@Override
				protected void onPostExecute(ArrayList<SifQuestionOptionsBean> result) {
					// TODO Auto-generated method stub
					super.onPostExecute(result);
					if (result != null) {
						if ("1".equals(taskBean.getGoBackSet()) && !"1".equals(taskQuestionBean.getOrderIndex())) {
							btnPrevious.setVisibility(View.VISIBLE);
						} else {
							btnPrevious.setVisibility(View.GONE);
						}
						if (taskQuestionBean.getOrderIndex().equals(questionBeans.size() + "")) {
							btnNext.setText(" 完成 ");
						}

						questionStr = taskQuestionBean.getQuestion();

						createOptions(taskQuestionBean.getQuestionType());
					}
				}
			}.execute();
		} else {
			Optionsbeans = new ArrayList<SifQuestionOptionsBean>();
			if (null != newOptionsbeans && newOptionsbeans.size() > 0) {
				for (int i = 0; i < newOptionsbeans.size(); i++) {
					SifQuestionOptionsBean optionsBean = newOptionsbeans.get(i);
					if (TaskQuestion_ID.equals(optionsBean.getTaskQuestion_ID())) {
						Optionsbeans.add(optionsBean);
					}
				}
			}
			if (null != Optionsbeans) {
				if ("1".equals(type) || "".equals(type) || null == type) {
					if ("1".equals(taskBean.getGoBackSet()) && !"1".equals(taskQuestionBean.getOrderIndex())) {
						btnPrevious.setVisibility(View.VISIBLE);
					} else {
						btnPrevious.setVisibility(View.GONE);
					}
				} else {
					if (!"1".equals(taskQuestionBean.getOrderIndex())) {
						btnPrevious.setVisibility(View.VISIBLE);
					} else {
						btnPrevious.setVisibility(View.GONE);
					}
				}

				if (taskQuestionBean.getOrderIndex().equals(questionBeans.size() + "")) {
					btnNext.setText(" 完成 ");
				}

				questionStr = taskQuestionBean.getQuestion();

				createOptions(taskQuestionBean.getQuestionType());
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.common, menu);
		return super.onCreateOptionsMenu(menu);
	}

	public View createView() {
		tv.setText(Task_Name);
		tv.setTextColor(this.getResources().getColor(R.color.white));
		tv.setTextSize(20);
		return tv;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated
															// method stub
		if (item.getItemId() == R.id.home) {
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public View createSpinnerView() {
		ImageView imageview = new ImageView(this);
		return imageview;
	}

	void savePictureSelf(String path) {
		QuestionAnswerDao answerDao = new QuestionAnswerDao(this);

		ArrayList<HashMap<String, String>> infos = SinofaithUtil.batchAnswer;
		for (HashMap<String, String> params : infos) {
			String Stemp_ID = params.get("Stemp_ID");
			QuestionAnswerBean bean = new QuestionAnswerBean();
			bean.setTask_ID(taskid);
			bean.setTaskQuestion_ID(taskQuestionBean.getTaskQuestion_ID());
			bean.setSubTask_ID(SubTask_ID);
			bean.setSubmiter(userMobile);
			bean.setStemp_ID(Stemp_ID);
			bean.setModifyTime(taskQuestionBean.getOrderIndex());
			if (Optionsbeans != null && Optionsbeans.size() > 0) {
				for (int i = 0; i < Optionsbeans.size(); i++) {
					SifQuestionOptionsBean optionsBean = Optionsbeans.get(i);
					if (optionsBean.getOptionValue().equals(path)) {
						bean.setRemindFlag(optionsBean.getRemindFlag());
					}
				}
			} else {
				bean.setRemindFlag("0");
			}
			bean.setGPS(SinofaithUtil.GPS);
			bean.setGPSTime(SinofaithUtil.getCurrentTime());
			bean.setIsFinish("0");
			bean.setFormto(previousHaspMap.get(currentPosition - 1) + "");
			if ("1".equals(batchflag)) {
				bean.setAnswerType("1");
			} else {
				bean.setAnswerType("0");
			}
			bean.setOtherAnswer("");
			// 检测是否存在已答
			String sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID = " + taskid
					+ " and SubTask_ID =  " + SubTask_ID;
			if (null != Stemp_ID && !"".equals(Stemp_ID)) {
				sql += " and Stemp_ID = " + Stemp_ID;
			}
			sql += " and TaskQuestion_ID = " + taskQuestionBean.getTaskQuestion_ID() + " and Submiter = " + userMobile;
			String answer = "";
			// 存在更新
			ArrayList<QuestionAnswerBean> answerList = answerDao.queryBySql(sql);
			if (answerList != null && answerList.size() > 0) {
				QuestionAnswerBean oldBean = answerList.get(0);
				String oldAnswer = oldBean.getAnswer();
				if (oldAnswer != null && oldAnswer.length() > 0) {
					answer = oldAnswer + "#" + path;
					String[] split = answer.split("#");
					bean.setFileCount(split.length + "");
					bean.setAnswer(answer);
				} else {
					bean.setAnswer(path);
				}
				bean.setID(oldBean.getID());
				bean.setIsFinish(oldBean.getIsFinish());
				answerDao.update(bean);
			} else { // 不存在insert
				bean.setFileCount("1");
				bean.setAnswer(path);
				answerDao.insert(bean);
			}

			if (taskQuestionBean.getOrderIndex().equals(questionBeans.size() + "")) {
				sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid + " and SubTask_ID="
						+ SubTask_ID;
				if (null != Stemp_ID && !"".equals(Stemp_ID)) {
					sql += " and Stemp_ID=" + Stemp_ID;
				}
				sql += " and Submiter=" + userMobile;
				answerList = answerDao.queryBySql(sql);
				if (null != answerList && answerList.size() > 0) {
					for (int i = 0; i < answerList.size(); i++) {
						QuestionAnswerBean oldBean = answerList.get(0);
						String oldAnswer = oldBean.getAnswer();
						if (oldAnswer != null && oldAnswer.length() > 0) {
							answer = oldAnswer + "#" + path;
							String[] split = answer.split("#");
							bean.setFileCount(split.length + "");
							bean.setAnswer(answer);
						} else {
							bean.setAnswer(path);
						}
						bean.setID(oldBean.getID());
						bean.setIsFinish("1");
						answerDao.update(bean);
					}
				} else {
					bean.setFileCount("1");
					bean.setIsFinish("1");
					bean.setAnswer(path);
					answerDao.insert(bean);
				}
			}

		}
	}

	// 缓存保存数据
	void saveData(final String answer, final String stemp_ID) {
		// 缓存
		SubAnswer = new ArrayList<AnswerReq>();
		QuestionAnswerBean answerBean = new QuestionAnswerBean();
		AnswerReq answerReq = new AnswerReq();
		answerBean.setTask_ID(taskid);
		answerBean.setTaskQuestion_ID(taskQuestionBean.getTaskQuestion_ID());
		answerBean.setSubTask_ID(SubTask_ID);
		answerBean.setSubmiter(userMobile);

		answerBean.setStemp_ID(Stemp_ID);
		// 媒体文件类题目
		if ("3".equals(taskQuestionBean.getQuestionType()) || "4".equals(taskQuestionBean.getQuestionType())
				|| "5".equals(taskQuestionBean.getQuestionType())) {
			if (!"".equals(answer)) {
				// String s = map.get(taskQuestionBean.getTaskQuestion_ID());
				String[] temps = answer.split("#");
				Log.i("TAG", "zaizhebian?");
				answerBean.setFileCount(temps.length + "");
				answerReq.setFileCount(temps.length + "");
			} else {
				answerBean.setFileCount("");
				answerReq.setFileCount("");
			}
		} else {
			answerBean.setFileCount("");
			answerReq.setFileCount("");
		}
		// 单选题有其他选项
		if ("1".equals(taskQuestionBean.getHasOtherOption()) && otherflag) {
			answerBean.setAnswer("其他");
			answerReq.setAnswer("其他");
			answerBean.setOtherAnswer(answer);
			answerReq.setOtherAnswer(answer);
		} else {
			answerBean.setAnswer(answer);
			answerReq.setAnswer(answer);
			answerBean.setOtherAnswer("");
			answerReq.setOtherAnswer("");
		}
		otherflag = false;
		// if("1".equals(autoflag)){
		// answerBean.setAnswerType("1");
		// }else{
		answerBean.setAnswerType("0");
		// }

		if ("1".equals(batchflag)) {
			answerBean.setAnswerType("1");
		} else {
			answerBean.setAnswerType("0");
		}

		answerBean.setIsFinish("0");
		answerBean.setFormto(previousHaspMap.get(currentPosition - 1) + "");
		answerReq.setTaskQuestion_ID(taskQuestionBean.getTaskQuestion_ID());

		answerReq.setQuestion(taskQuestionBean.getQuestion());
		answerReq.setQuestionType(taskQuestionBean.getQuestionType());
		answerReq.setOrder(taskQuestionBean.getOrderIndex());
		answerBean.setGPS(SinofaithUtil.GPS);
		answerBean.setGPSTime(SinofaithUtil.getCurrentTime());
		answerReq.setGPS(SinofaithUtil.GPS);
		answerReq.setGPSTime(SinofaithUtil.getCurrentTime());
		answerBean.setModifyTime(taskQuestionBean.getOrderIndex());
		if (Optionsbeans != null && Optionsbeans.size() > 0) {
			for (int i = 0; i < Optionsbeans.size(); i++) {
				SifQuestionOptionsBean optionsBean = Optionsbeans.get(i);
				if (optionsBean.getOptionValue().equals(answer)) {
					answerBean.setRemindFlag(optionsBean.getRemindFlag());
				}
			}
		} else {
			answerBean.setRemindFlag("0");
		}

		// 检测本地是否已答,并执行增加/更新操作
		QuestionAnswerDao answerDao = new QuestionAnswerDao(AnswerQuestionActivity.this);
		String sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid + " and SubTask_ID="
				+ SubTask_ID;
		if (null != Stemp_ID && !"".equals(Stemp_ID)) {
			sql += " and Stemp_ID=" + Stemp_ID;
		}
		sql += " and TaskQuestion_ID=" + taskQuestionBean.getTaskQuestion_ID() + " and Submiter=" + userMobile;
		List<QuestionAnswerBean> answerlist = answerDao.queryBySql(sql);
		// Log.v("qqqq",
		// answerlist.get(0).getTask_ID()+"==="+answerlist.get(0).getTaskQuestion_ID()+"==="+answerlist.get(0).getAnswer());
		if (null != answerlist && answerlist.size() > 0) {
			QuestionAnswerBean oldanswerBean = answerlist.get(0);
			answerBean.setID(oldanswerBean.getID());
			answerBean.setIsFinish(oldanswerBean.getIsFinish());
			answerDao.update(answerBean);
		} else {
			answerDao.insert(answerBean);
		}

		sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid + " and SubTask_ID="
				+ SubTask_ID;
		if (null != Stemp_ID && !"".equals(Stemp_ID)) {
			sql += " and Stemp_ID=" + Stemp_ID;
		}
		sql += " and Submiter=" + userMobile;
		answerlist = answerDao.queryBySql(sql);
		answerBean = new QuestionAnswerBean();
		if (null != answerlist && answerlist.size() > 0) {
			for (int i = 0; i < answerlist.size(); i++) {
				answerBean = answerlist.get(i);
				if ("1".equals(batchflag)) {
					answerBean.setAnswerType("1");
				} else {
					answerBean.setAnswerType("0");
				}
				answerDao.update(answerBean);
			}
		}

		// 当前题目为最后一题时
		if (taskQuestionBean.getOrderIndex().equals(questionBeans.size() + "")) {
			sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid + " and SubTask_ID="
					+ SubTask_ID;
			if (null != Stemp_ID && !"".equals(Stemp_ID)) {
				sql += " and Stemp_ID=" + Stemp_ID;
			}
			sql += " and Submiter=" + userMobile;
			answerlist = answerDao.queryBySql(sql);
			answerBean = new QuestionAnswerBean();
			if (null != answerlist && answerlist.size() > 0) {
				for (int i = 0; i < answerlist.size(); i++) {
					answerBean = answerlist.get(i);
					answerBean.setIsFinish("1");
					answerDao.update(answerBean);
				}
			}
		}
		mLoadingDialog.dismiss();
	}

	void batchSaveData(String answer, String stemps) {
		if ("3".equals(taskQuestionBean.getQuestionType())) {
			return;
		}
		// 检测本地是否已答,并执行增加/更新操作
		QuestionAnswerDao answerDao = new QuestionAnswerDao(AnswerQuestionActivity.this);
		// String sql = "select * from " + QuestionAnswerBean.TABLENAME
		// + " where Task_ID=" + taskid + " and SubTask_ID=" + SubTask_ID +
		// " and";
		// if (null != stemps && !"".equals(stemps)) {
		// sql+=" Stemp_ID in ("+stemps+")";
		// }
		// sql += " and TaskQuestion_ID=" +
		// taskQuestionBean.getTaskQuestion_ID()
		// + " and Submiter=" + SinofaithUtil.userInfo.getUserMobile();
		// List<QuestionAnswerBean> answerlist = answerDao.queryBySql(sql);
		// if (null != answerlist && answerlist.size() > 0) {
		String sql = "";
		List<QuestionAnswerBean> answerlist = new ArrayList<QuestionAnswerBean>();
		String FileCount = "";
		String OtherAnswer = "";
		String RemindFlag = "0";
		String Formto = "";
		answer = answer == null ? "" : answer;
		// 媒体文件类题目
		if ("3".equals(taskQuestionBean.getQuestionType()) || "4".equals(taskQuestionBean.getQuestionType())
				|| "5".equals(taskQuestionBean.getQuestionType())) {
			if (null != answer && !"".equals(answer)) {
				int index = answer.indexOf("#");
				if (index >= 0) {
					String[] temps = answer.split("#");
					FileCount = temps.length + "";
				} else {
					FileCount = "1";
				}
			}
		}
		// 单选题有其他选项
		if ("1".equals(taskQuestionBean.getHasOtherOption()) && otherflag) {
			OtherAnswer = answer;
			answer = "其他";
		}
		if (Optionsbeans != null && Optionsbeans.size() > 0) {
			for (int i = 0; i < Optionsbeans.size(); i++) {
				SifQuestionOptionsBean optionsBean = Optionsbeans.get(i);
				if (optionsBean.getOptionValue().equals(answer)) {
					RemindFlag = optionsBean.getRemindFlag();
				}
			}
		}
		if (null != previousHaspMap && null != previousHaspMap.get(currentPosition - 1)) {
			Formto = previousHaspMap.get(currentPosition - 1) + "";
		}
		// ?
		sql = "update " + QuestionAnswerBean.TABLENAME + " set Answer='" + answer + "', FileCount='" + FileCount
				+ "', OtherAnswer='" + OtherAnswer + "', AnswerType='1', IsFinish='0', Formto='" + Formto + "', GPS='"
				+ SinofaithUtil.GPS + "', RemindFlag='" + RemindFlag + "' where ";
		sql += "Task_ID='" + taskid + "' and SubTask_ID='" + SubTask_ID + "'";
		if (null != stemps && !"".equals(stemps)) {
			sql += " and Stemp_ID in (" + stemps + ")";
		}
		sql += " and TaskQuestion_ID='" + taskQuestionBean.getTaskQuestion_ID() + "' and Submiter='" + userMobile + "'";

		int result = answerDao.update(sql);
		Log.v("qqqq", sql + "=====" + result);
		// 当前题目为最后一题时
		if (taskQuestionBean.getOrderIndex().equals(questionBeans.size() + "")) {
			sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid + " and SubTask_ID="
					+ SubTask_ID;
			if (null != stemps && !"".equals(stemps)) {
				sql += " and Stemp_ID in (" + stemps + ")";
			}
			sql += " and Submiter=" + userMobile + " and IsFinish<>2";
			answerlist = answerDao.queryBySql(sql);
			if (null != answerlist && answerlist.size() > 0) {
				// String ID="";
				for (int i = 0; i < answerlist.size(); i++) {
					// QuestionAnswerBean oldanswerBean = answerlist.get(i);
					// ID+=oldanswerBean.getID()+",";
					QuestionAnswerBean answerBean = answerlist.get(i);
					answerBean.setIsFinish("1");
					answerDao.update(answerBean);
				}
				// ID=ID.substring(0,ID.length()-1);
				// sql="update " + QuestionAnswerBean.TABLENAME
				// + " set IsFinish=1 where ";
				// if (null != stemps && !"".equals(stemps)) {
				// sql+=" ID in ("+ID+")";
				// }
				// Log.v("qqqq",sql);
				// answerDao.update(sql);

			}
		} else {

		}
		// }
	}

	void clearAnswer(String first, String end, String Stemp_ID) {
		QuestionAnswerDao answerDao = new QuestionAnswerDao(AnswerQuestionActivity.this);
		answerDao.delete(taskid, SubTask_ID, Stemp_ID, userMobile, first, end);
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.btnNext:
			if (isFirstDo) {
				changeTaskFirstModifyTime();
				isFirstDo = false;
			}
			// 问题编号
			final String answer = map.get(taskQuestionBean.getTaskQuestion_ID());

			previousQid = taskQuestionBean.getOrderIndex();
			taskQuestionID = taskQuestionBean.getTaskQuestion_ID();
			if (null != answer) {
				if (null != SinofaithUtil.batchAnswer && SinofaithUtil.batchAnswer.size() > 0) {
					String stemps = "";
					for (int i = 0; i < SinofaithUtil.batchAnswer.size(); i++) {
						HashMap<String, String> batchMap = SinofaithUtil.batchAnswer.get(i);
						stemps += batchMap.get("Stemp_ID") + ",";
					}
					stemps = stemps.substring(0, stemps.length() - 1);
					batchSaveData(answer, stemps);
				} else {
					saveData(answer, Stemp_ID);
				}

				// 当前题目为最后一题时
				if (taskQuestionBean.getOrderIndex().equals(questionBeans.size() + "")) {
					btnNext.setEnabled(false);
					String sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid
							+ " and SubTask_ID=" + SubTask_ID;
					if (null != Stemp_ID && !"".equals(Stemp_ID)) {
						sql += " and Stemp_ID=" + Stemp_ID;
					}
					sql += " and Submiter=" + userMobile;
					QuestionAnswerDao answerDao = new QuestionAnswerDao(AnswerQuestionActivity.this);
					List<QuestionAnswerBean> answerlist = answerDao.queryBySql(sql);
					QuestionAnswerBean answerBean = new QuestionAnswerBean();
					Log.i("jsc-GPS-Time","答案的个数answerlist.size():"+answerlist.size());
					if (null != answerlist && answerlist.size() > 0) {
						SubAnswer = new ArrayList<AnswerReq>();
						for (int i = 0; i < answerlist.size(); i++) {
							answerBean = answerlist.get(i);
							// answerBean.setIsFinish("1");
							// answerDao.update(answerBean);
							AnswerReq answerReq = new AnswerReq();
							SifTaskQuestionBean taskQBean = new SifTaskQuestionBean();
							if (null != questionBeans && questionBeans.size() > 0) {
								for (int j = 0; j < questionBeans.size(); j++) {
									taskQBean = questionBeans.get(j);
									if (taskQBean.getTaskQuestion_ID().equals(answerBean.getTaskQuestion_ID())) {
										break;
									}
								}
							}
							// 媒体文件类题目
							if ("3".equals(taskQBean.getQuestionType()) || "4".equals(taskQBean.getQuestionType())
									|| "5".equals(taskQBean.getQuestionType())) {
								if (null == answerBean.getAnswer() || "".equals(answerBean.getAnswer())) {
									answerReq.setFileCount("");
								} else {
									String s = answerBean.getAnswer();
									if (s.indexOf("#") >= 0) {
										String[] temps = s.split("#");
										answerReq.setFileCount(temps.length + "");
									} else {
										answerReq.setFileCount("1");
									}
								}
							} else {
								answerReq.setFileCount("");
							}
							// 单选题有其他选项
							if ("1".equals(taskQBean.getHasOtherOption()) && otherflag) {
								answerReq.setAnswer("");
								answerReq.setOtherAnswer(answerBean.getAnswer());
							} else {
								answerReq.setAnswer(answerBean.getAnswer());
								answerReq.setOtherAnswer("");
							}
							answerReq.setTaskQuestion_ID(taskQBean.getTaskQuestion_ID());
							answerReq.setQuestion(taskQBean.getQuestion());
							answerReq.setQuestionType(taskQBean.getQuestionType());
							answerReq.setOrder(taskQBean.getOrderIndex());
							answerReq.setGPS(answerBean.getGPS());
							answerReq.setGPSTime(answerBean.getGPSTime());
							SubAnswer.add(answerReq);
						}
					}
					if (null != SinofaithUtil.batchAnswer && SinofaithUtil.batchAnswer.size() > 0) {
						Toast.makeText(this, "批量答题请在列表中进行提交", Toast.LENGTH_LONG).show();
						AnswerQuestionActivity.this.finish();
					} else {
						Intent intent = new Intent(AnswerQuestionActivity.this, AnswerFinishActivity.class);
						intent.putExtra("Task_Name", Task_Name);
						answerReqBean.setSubAnswer(SubAnswer);
						Log.i("jsc-GPS-Time", "跳转传入的值："+answerReqBean.toString());
						intent.putExtra("answerReqBean", answerReqBean);
						intent.putExtra("answerBean", answerBean);
						AnswerQuestionActivity.this.startActivity(intent);
						AnswerQuestionActivity.this.finish();
					}

				} else {
					// 不是最后一道题 .下一题按钮可以继续按
					btnNext.setEnabled(true);
					// 非选择类题目
					if (Integer.valueOf(taskQuestionBean.getQuestionType()) > 1) {
						int tqid = Integer.valueOf(taskQuestionBean.getOrderIndex());
						if (null != taskQuestionBean.getJumpTo() && !"".equals(taskQuestionBean.getJumpTo())) {
							tqid = Integer.valueOf(taskQuestionBean.getJumpTo()) - 1;
						}
						if (tqid < 0) {
							tqid = Integer.valueOf(taskQuestionBean.getOrderIndex());
						}
						jumpTo = taskQuestionBean.getJumpTo();
						taskQuestionBean = questionBeans.get(tqid);
						getOptions(taskQuestionBean.getTaskQuestion_ID());
					} else {
						// 根据选项跳转至不同题目
						int tqid = Integer.valueOf(taskQuestionBean.getOrderIndex());
						for (int i = 0; i < Optionsbeans.size(); i++) {
							questionOptionsBean = Optionsbeans.get(i);
							if (answer.equals(questionOptionsBean.getOptionValue())) {
								if (null != questionOptionsBean.getJumpTo()
										&& !"".equals(questionOptionsBean.getJumpTo())) {
									tqid = Integer.valueOf(questionOptionsBean.getJumpTo()) - 1;
								}
								if (tqid < 0) {
									tqid = Integer.valueOf(taskQuestionBean.getOrderIndex());
								}
								jumpTo = questionOptionsBean.getJumpTo();
								break;
							}
						}
						taskQuestionBean = questionBeans.get(tqid);

						getOptions(taskQuestionBean.getTaskQuestion_ID());
					}
					currentPosition++;
					previousHaspMap.put(currentPosition, Integer.valueOf(previousQid));

					// 清空跳转时原未跳转部分答题数据
					if (null == previousQid || "".equals(previousQid)) {
						previousQid = "1";
					}
					String first = "";
					if (null == jumpTo || "".equals(jumpTo)) {
						first = taskQuestionBean.getOrderIndex();
					} else {
						first = jumpTo;
					}
					if ((Integer.valueOf(first) - Integer.valueOf(previousQid)) > 1) {
						if (null != SinofaithUtil.batchAnswer && SinofaithUtil.batchAnswer.size() > 0) {
							String stemps = "";
							for (int i = 0; i < SinofaithUtil.batchAnswer.size(); i++) {
								HashMap<String, String> batchMap = SinofaithUtil.batchAnswer.get(i);
								stemps += batchMap.get("Stemp_ID") + ",";
								clearAnswer(previousQid, taskQuestionBean.getOrderIndex(), batchMap.get("Stemp_ID"));
							}
							stemps = stemps.substring(0, stemps.length() - 1);
							String end = (Integer.valueOf(taskQuestionBean.getOrderIndex())
									- Integer.valueOf(previousQid)) + "";
						} else {
							String end = (Integer.valueOf(taskQuestionBean.getOrderIndex())
									- Integer.valueOf(previousQid)) + "";
							clearAnswer(previousQid, taskQuestionBean.getOrderIndex(), Stemp_ID);
						}
					}
				}

			} else {
				// 当前题目为必答时
				if ("1".equals(taskQuestionBean.getIsRequired())) {
					Toast.makeText(AnswerQuestionActivity.this, "该题为必答题，请先回答后再进入下一题", Toast.LENGTH_LONG).show();
					return;
				} else {
					// 缓存
					if (null != SinofaithUtil.batchAnswer && SinofaithUtil.batchAnswer.size() > 0) {
						String stemps = "";
						for (int i = 0; i < SinofaithUtil.batchAnswer.size(); i++) {
							HashMap<String, String> batchMap = SinofaithUtil.batchAnswer.get(i);
							stemps += batchMap.get("Stemp_ID") + ",";
						}
						stemps = stemps.substring(0, stemps.length() - 1);
						batchSaveData(answer, stemps);
					} else {
						saveData("", Stemp_ID);
					}
					// // 当前题目为最后一题时
					if (taskQuestionBean.getOrderIndex().equals(questionBeans.size() + "")) {
						btnNext.setEnabled(false);
						String sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid
								+ " and SubTask_ID=" + SubTask_ID;
						if (null != Stemp_ID && !"".equals(Stemp_ID)) {
							sql += " and Stemp_ID=" + Stemp_ID;
						}
						sql += " and Submiter=" + userMobile;
						QuestionAnswerDao answerDao = new QuestionAnswerDao(AnswerQuestionActivity.this);
						List<QuestionAnswerBean> answerlist = answerDao.queryBySql(sql);
						QuestionAnswerBean answerBean = new QuestionAnswerBean();
						if (null != answerlist && answerlist.size() > 0) {
							SubAnswer = new ArrayList<AnswerReq>();
							for (int i = 0; i < answerlist.size(); i++) {
								answerBean = answerlist.get(i);
								// answerBean.setIsFinish("1");
								// answerDao.update(answerBean);
								AnswerReq answerReq = new AnswerReq();
								SifTaskQuestionBean taskQBean = new SifTaskQuestionBean();
								if (null != questionBeans && questionBeans.size() > 0) {
									for (int j = 0; j < questionBeans.size(); j++) {
										taskQBean = questionBeans.get(j);
										if (taskQBean.getTaskQuestion_ID().equals(answerBean.getTaskQuestion_ID())) {
											break;
										}
									}
								}
								// 媒体文件类题目
								if ("3".equals(taskQBean.getQuestionType()) || "4".equals(taskQBean.getQuestionType())
										|| "5".equals(taskQBean.getQuestionType())) {

									if (null == answerBean.getAnswer() || "".equals(answerBean.getAnswer())) {
										answerReq.setFileCount("");
									} else {
										String s = answerBean.getAnswer();
										if (s.indexOf("#") >= 0) {
											String[] temps = s.split("#");
											answerReq.setFileCount(temps.length + "");
										} else {
											answerReq.setFileCount("1");
										}
									}

								} else {
									answerReq.setFileCount("");
								}
								// 单选题有其他选项
								if ("1".equals(taskQBean.getHasOtherOption()) && otherflag) {
									answerReq.setAnswer("");
									answerReq.setOtherAnswer(answerBean.getAnswer());
								} else {
									answerReq.setAnswer(answerBean.getAnswer());
									answerReq.setOtherAnswer("");
								}
								answerReq.setTaskQuestion_ID(taskQBean.getTaskQuestion_ID());
								answerReq.setQuestion(taskQBean.getQuestion());
								answerReq.setQuestionType(taskQBean.getQuestionType());
								answerReq.setOrder(taskQBean.getOrderIndex());
								answerReq.setGPS(answerBean.getGPS());
								answerReq.setGPSTime(answerBean.getGPSTime());
								SubAnswer.add(answerReq);
							}
						}
						if (null != SinofaithUtil.batchAnswer && SinofaithUtil.batchAnswer.size() > 0) {
							Toast.makeText(this, "批量答题请在列表中进行提交", Toast.LENGTH_LONG).show();
							AnswerQuestionActivity.this.finish();
						} else {
							Intent intent = new Intent(AnswerQuestionActivity.this, AnswerFinishActivity.class);
							intent.putExtra("Task_Name", Task_Name);
							answerReqBean.setSubAnswer(SubAnswer);
							Log.i("jsc-GPS-Time", "跳转传入的值2："+answerReqBean.toString());
							intent.putExtra("answerReqBean", answerReqBean);
							intent.putExtra("answerBean", answerBean);
							AnswerQuestionActivity.this.startActivity(intent);
							AnswerQuestionActivity.this.finish();
						}
					} else {
						btnNext.setEnabled(true);
						currentPosition++;
						previousHaspMap.put(currentPosition, Integer.valueOf(previousQid));
						// 非选择类题目
						if (Integer.valueOf(taskQuestionBean.getQuestionType()) > 1) {
							int tqid = Integer.valueOf(taskQuestionBean.getOrderIndex());
							if (null != taskQuestionBean.getJumpTo() && !"".equals(taskQuestionBean.getJumpTo())) {
								tqid = Integer.valueOf(taskQuestionBean.getJumpTo()) - 1;
							}
							if (tqid < 0) {
								tqid = Integer.valueOf(taskQuestionBean.getOrderIndex());
							}
							jumpTo = taskQuestionBean.getJumpTo();
							taskQuestionBean = questionBeans.get(tqid);
							getOptions(taskQuestionBean.getTaskQuestion_ID());
						} else {
							// 根据选项跳转至不同题目
							int tqid = Integer.valueOf(taskQuestionBean.getOrderIndex());
							jumpTo = taskQuestionBean.getOrderIndex();
							taskQuestionBean = questionBeans.get(tqid);

							getOptions(taskQuestionBean.getTaskQuestion_ID());
						}

						// 清空跳转时原未跳转部分答题数据
						if (null == previousQid || "".equals(previousQid)) {
							previousQid = "1";
						}
						String first = "";
						if (null == jumpTo || "".equals(jumpTo)) {
							first = taskQuestionBean.getOrderIndex();
						} else {
							first = jumpTo;
						}
						if ((Integer.valueOf(first) - Integer.valueOf(previousQid)) > 1) {
							if (null != SinofaithUtil.batchAnswer && SinofaithUtil.batchAnswer.size() > 0) {
								String stemps = "";
								for (int i = 0; i < SinofaithUtil.batchAnswer.size(); i++) {
									HashMap<String, String> batchMap = SinofaithUtil.batchAnswer.get(i);
									stemps += batchMap.get("Stemp_ID") + ",";
									clearAnswer(previousQid, taskQuestionBean.getOrderIndex(),
											batchMap.get("Stemp_ID"));
								}
								stemps = stemps.substring(0, stemps.length() - 1);
								String end = (Integer.valueOf(taskQuestionBean.getOrderIndex())
										- Integer.valueOf(previousQid)) + "";
							} else {
								String end = (Integer.valueOf(taskQuestionBean.getOrderIndex())
										- Integer.valueOf(previousQid)) + "";
								clearAnswer(previousQid, taskQuestionBean.getOrderIndex(), Stemp_ID);
							}
						}
					}

				}
			}

			break;
		case R.id.btnPrevious:
			if (null != previousHaspMap.get(currentPosition) && !"".equals(previousHaspMap.get(currentPosition))) {

				// 上一题
				previousQid = previousHaspMap.get(currentPosition) + "";
				taskQuestionBean = questionBeans.get(Integer.valueOf(previousQid) - 1);
				getOptions(taskQuestionBean.getTaskQuestion_ID());
				btnNext.setText("下一题");
				currentPosition--;
				previousQid = previousHaspMap.get(currentPosition) + "";
				// if(!"1".equals(type)){
				QuestionAnswerDao answerDao = new QuestionAnswerDao(this);
				String sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid
						+ " and SubTask_ID=" + SubTask_ID;
				if (null != Stemp_ID && !"".equals(Stemp_ID)) {
					sql += " and Stemp_ID=" + Stemp_ID;
				}
				sql += " and TaskQuestion_ID=" + taskQuestionBean.getTaskQuestion_ID() + " and Submiter=" + userMobile;
				ArrayList<QuestionAnswerBean> answerBeans = answerDao.queryBySql(sql);
				if (null != answerBeans && answerBeans.size() > 0) {
					previousAnswerBean = answerBeans.get(0);
				}
				// }
			}
			break;
		}
	}

	Uri originalUri;

	void createOptions(String qtype) {
		lstImageItem = new ArrayList<HashMap<String, Object>>();
		String ht = "";
		if (null != taskQuestionBean.getIsRequired() && taskQuestionBean.getIsRequired().equals("1")) {
			ht = "  <font color='red'>*</font>";
		}
		questionName
				.setText(Html.fromHtml(taskQuestionBean.getOrderIndex() + "、" + taskQuestionBean.getQuestion() + ht));
		tv_progress.setText(taskQuestionBean.getOrderIndex() + "/" + questionBeans.size());
		if (!"2".equals(flag)) {
			QuestionAnswerDao answerDao = new QuestionAnswerDao(this);
			String sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid
					+ " and SubTask_ID=" + SubTask_ID;
			if (null != Stemp_ID && !"".equals(Stemp_ID)) {
				sql += " and Stemp_ID=" + Stemp_ID;
			}
			sql += " and TaskQuestion_ID=" + taskQuestionBean.getTaskQuestion_ID() + " and Submiter=" + userMobile;
			ArrayList<QuestionAnswerBean> answerBeans = answerDao.queryBySql(sql);
			if (null != answerBeans && answerBeans.size() > 0) {
				previousAnswerBean = answerBeans.get(0);
			}
		}

		if (null == map) {
			map = new HashMap<String, String>();
		}

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT);

		linearLayout.removeAllViews();
		if ("1".equals(qtype)) { // 动态创建单选按钮
			Log.i("TAG", "just a option");
			final EditText editText = new EditText(this);
			linearLayout.setOrientation(LinearLayout.VERTICAL);
			RadioGroup radioGroup = new RadioGroup(this);
			// params.addRule(LinearLayout.CENTER_HORIZONTAL,LinearLayout.TRUE);
			radioGroup.setLayoutParams(params);
			for (int i = 0; i < Optionsbeans.size(); i++) {
				questionOptionsBean = Optionsbeans.get(i);
				RadioButton radioButton = new RadioButton(this);
				radioButton.setId(1000 + i);
				radioButton.setText(questionOptionsBean.getOptionValue());
				if (null != previousAnswerBean) {
					if (previousAnswerBean.getAnswer().equals(questionOptionsBean.getOptionValue())
							&& previousAnswerBean.getTaskQuestion_ID()
									.equals(questionOptionsBean.getTaskQuestion_ID())) {
						radioButton.setChecked(true);
						map.put(taskQuestionBean.getTaskQuestion_ID(), radioButton.getText().toString());
					}
				}
				radioGroup.addView(radioButton);
			}
			linearLayout.addView(radioGroup);

			if ("1".equals(taskQuestionBean.getHasOtherOption())) {
				RadioButton radioButton = new RadioButton(this);
				radioButton.setId(2000);
				radioButton.setText("其他");
				if (null != previousAnswerBean) {
					if (previousAnswerBean.getAnswer().equals("其他") && previousAnswerBean.getTaskQuestion_ID()
							.equals(questionOptionsBean.getTaskQuestion_ID())) {
						radioButton.setChecked(true);
						map.put(taskQuestionBean.getTaskQuestion_ID(), previousAnswerBean.getOtherAnswer());
						otherflag = true;
					}
				}
				radioGroup.addView(radioButton);

				editText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
				editText.setGravity(Gravity.TOP);
				// 改变默认的单行模式
				editText.setSingleLine(false);
				// 水平滚动设置为False
				editText.setHorizontallyScrolling(false);
				editText.setMinLines(4);
				// editText.setMaxLines(1);
				editText.setLayoutParams(params);
				if (null != previousAnswerBean) {
					if (previousAnswerBean.getAnswer().equals("其他") && previousAnswerBean.getTaskQuestion_ID()
							.equals(questionOptionsBean.getTaskQuestion_ID())) {
						editText.setText(previousAnswerBean.getOtherAnswer());
					}
				}
				linearLayout.addView(editText);
			}

			radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(RadioGroup group, int checkedId) {
					RadioButton radioButton = (RadioButton) findViewById(group.getCheckedRadioButtonId());
					if (radioButton.getText().equals("其他") && "1".equals(taskQuestionBean.getHasOtherOption())) {
						editText.addTextChangedListener(new TextWatcher() {
							@Override
							public void onTextChanged(CharSequence s, int start, int before, int count) {
								// if(count>0){
								otherflag = true;
								map.put(taskQuestionBean.getTaskQuestion_ID(), s.toString());
								// }
							}

							@Override
							public void beforeTextChanged(CharSequence s, int start, int count, int after) {

								map.put(taskQuestionBean.getTaskQuestion_ID(), s.toString());
							}

							@Override
							public void afterTextChanged(Editable s) {
								//
								// map.put(nurseItem.getName(),
								// s.toString());
							}
						});
					} else {
						map.put(taskQuestionBean.getTaskQuestion_ID(), radioButton.getText().toString());
					}
				}
			});
		} else if ("2".equals(qtype)) { // 动态创建复选框
			Log.i("TAG", "group radio?");
			linearLayout.setOrientation(LinearLayout.VERTICAL);
			temp = "";
			for (int i = 0; i < Optionsbeans.size(); i++) {
				questionOptionsBean = Optionsbeans.get(i);
				String[] temps = null;
				if (null != previousAnswerBean
						&& previousAnswerBean.getTaskQuestion_ID().equals(taskQuestionBean.getTaskQuestion_ID())) {
					temps = previousAnswerBean.getAnswer().split("#");
				}

				CheckBox checkBox = new CheckBox(this);
				checkBox.setId(3000 + i);
				checkBox.setText(questionOptionsBean.getOptionValue());
				if (null != temps && temps.length > 0) {
					for (int t = 0; t < temps.length; t++) {
						if (questionOptionsBean.getOptionValue().equals(temps[t]) && previousAnswerBean
								.getTaskQuestion_ID().equals(taskQuestionBean.getTaskQuestion_ID())) {
							checkBox.setChecked(true);
							temp += ("#" + temps[t]);
						} else {
							// String[] str = temp.split("#");
							// temp = "";
							// for (int j = 0; j < str.length; j++) {
							// if (str[j].equals(temps[t])) {
							// // 不作处理（即：当选中之后再次点击时，这条数据不再重新累加进temp字符串中）
							// } else {
							// temp += "#" + str[j];
							// }
							//
							// }
						}
					}
					if (temp.length() > 0) {
						if (temp.substring(0, 1).equals("#")) {
							temp = temp.substring(1);
						}
					}
					map.put(taskQuestionBean.getTaskQuestion_ID(), temp);
				}
				checkBox.setLayoutParams(params);
				// linearLayout.addView(checkBox);
				// mViewHolder.linearLayout.addView(linearLayout,lp2);
				linearLayout.addView(checkBox);

				checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

						if (null == map) {
							map = new HashMap<String, String>();
						}

						if (isChecked) {
							temp += ("#" + buttonView.getText().toString());
						} else {
							String[] str = temp.split("#");
							temp = "";
							for (int i = 0; i < str.length; i++) {
								if (str[i].equals(buttonView.getText().toString())) {
									// 不作处理（即：当选中之后再次点击时，这条数据不再重新累加进temp字符串中）
								} else {
									temp += "#" + str[i];
								}

							}
						}
						if (temp.length() > 0) {
							if (temp.substring(0, 1).equals("#")) {
								temp = temp.substring(1);
							}
						}
						map.put(taskQuestionBean.getTaskQuestion_ID(), temp);
					}
				});
			}

		} else if ("3".equals(qtype)) { // 动态创建图片上传
			// linearLayout.setOrientation(LinearLayout.HORIZONTAL);
			Log.i("TAG", "take photo?");
			linearLayout.setLayoutParams(params);
			if (null != taskQuestionBean.getPhotoNum() && !"".equals(taskQuestionBean.getPhotoNum())) {
				PhotoNum = Integer.valueOf(taskQuestionBean.getPhotoNum());
			}
			count = 0;
			imgtemp = "";
			PhotoMode = taskQuestionBean.getPhotoMode();
           // Log.i("jsc", "answer:"+previousAnswerBean.getAnswer());
			gridView.setNumColumns(4);
			gridView.setVerticalSpacing(10);
			gridView.setLayoutParams(params);
			String[] temps = null;
			if (null != previousAnswerBean
					&& previousAnswerBean.getTaskQuestion_ID().equals(taskQuestionBean.getTaskQuestion_ID())
					&& !"".equals(previousAnswerBean.getAnswer())) {
				temps = previousAnswerBean.getAnswer().split("#");
				Log.i("TAG", previousAnswerBean.getAnswer());
				count = temps.length;
				if (null != temps && temps.length > 0) {
					for (int t = 0; t < temps.length; t++) {
						if (null != temps[t] && !"".equals(temps[t])) {
						     Log.i("jsc", "temps:"+temps[t]);
							HashMap<String, Object> hashMap = new HashMap<String, Object>();
							hashMap.put("ItemImage", temps[t]);
							hashMap.put("ItemText", temps[t]);
							lstImageItem.add(hashMap);

							map.put(taskQuestionBean.getTaskQuestion_ID(), previousAnswerBean.getAnswer());
							imgtemp = previousAnswerBean.getAnswer();
						}
					}
				
					SimpleAdapter saImageItems = new SimpleAdapter(this, // 没什么解释
							lstImageItem, // 数据来源
							R.layout.night_item, // night_item的XML实现
							// 动态数组与ImageItem对应的子项
							new String[] { "ItemImage", "ItemText" }, new int[] { R.id.ItemImage, R.id.ItemText });

					gridView.setAdapter(saImageItems);
				}
			}

			if (count == PhotoNum) {

			} else {
				HashMap<String, Object> hashMap = new HashMap<String, Object>();
				hashMap.put("ItemImage", R.drawable.camera);
				hashMap.put("ItemText", "button");
				lstImageItem.add(hashMap);
				SimpleAdapter saImageItems = new SimpleAdapter(this, // 没什么解释
						lstImageItem, // 数据来源
						R.layout.night_item, // night_item的XML实现
						// 动态数组与ImageItem对应的子项
						new String[] { "ItemImage", "ItemText" }, new int[] { R.id.ItemImage, R.id.ItemText });

				gridView.setAdapter(saImageItems);
			}
			gridView.setOnItemClickListener(new ItemClickListener());
			gridView.setOnItemLongClickListener(new ImageLongClickListener());
			linearLayout.removeAllViews();
			linearLayout.addView(gridView);
		} else if ("4".equals(qtype)) { // 动态创建音频上传
			Log.i("TAG", "audio ");
			linearLayout.setOrientation(LinearLayout.HORIZONTAL);
			if (null != previousAnswerBean
					&& previousAnswerBean.getTaskQuestion_ID().equals(taskQuestionBean.getTaskQuestion_ID())) {
				if (null != previousAnswerBean.getAnswer() && !"".equals(previousAnswerBean.getAnswer())) {
					Display mDisplay = getWindowManager().getDefaultDisplay();
					int W = mDisplay.getWidth();
					RelativeLayout.LayoutParams relparams = new RelativeLayout.LayoutParams(W / 4, W / 4);
					linearLayout.setOrientation(LinearLayout.HORIZONTAL);
					ImageView imageView = new ImageView(this);
					relparams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
					imageView.setPadding(20, 0, 20, 0);
					imageView.setScaleType(ImageView.ScaleType.FIT_XY);
					imageView.setBackgroundResource(R.drawable.audio_icon);
					linearLayout.addView(imageView, relparams);
					map.put(taskQuestionBean.getTaskQuestion_ID(), previousAnswerBean.getAnswer());
					imageView.setOnLongClickListener(new AudioLongClickListener());
				}
			}
			button = new Button(this);
			button.setId(20000);
			button.setBackgroundResource(R.drawable.audio);
			if (null != previousAnswerBean
					&& previousAnswerBean.getTaskQuestion_ID().equals(taskQuestionBean.getTaskQuestion_ID())) {
				if (null != previousAnswerBean.getAnswer() && !"".equals(previousAnswerBean.getAnswer())) {
					button.setVisibility(View.GONE);
				} else {
					button.setVisibility(View.VISIBLE);
				}

			}
			linearLayout.addView(button);
			button.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					MyDialog.Builder builder = new MyDialog.Builder(AnswerQuestionActivity.this);
					builder.setTitle("选择录音来源")
							.setPositiveButton("本地", new android.content.DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									Intent picture = new Intent(Intent.ACTION_PICK,
											android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
									startActivityForResult(picture, REQUEST_CODE_AUDIO);
									dialog.dismiss();
								}
							}).setNegativeButton("实时", new android.content.DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									Intent audiorecord = new Intent(AnswerQuestionActivity.this, AudioRecord.class);
									startActivityForResult(audiorecord, REQUEST_CODE_AUDIO);
									dialog.dismiss();
								}
							});
					Dialog dialog = builder.create();
					dialog.show();
				}
			});
		} else if ("5".equals(qtype)) { // 动态创建视频上传
			Log.i("TAG", "video");
			linearLayout.setOrientation(LinearLayout.HORIZONTAL);
			if (null != previousAnswerBean
					&& previousAnswerBean.getTaskQuestion_ID().equals(taskQuestionBean.getTaskQuestion_ID())) {
				if (null != previousAnswerBean.getAnswer() && !"".equals(previousAnswerBean.getAnswer())) {
					Display mDisplay = getWindowManager().getDefaultDisplay();
					int W = mDisplay.getWidth();
					RelativeLayout.LayoutParams relparams = new RelativeLayout.LayoutParams(W / 4, W / 4);
					linearLayout.setOrientation(LinearLayout.HORIZONTAL);
					ImageView imageView = new ImageView(this);
					relparams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
					imageView.setPadding(20, 0, 20, 0);
					imageView.setScaleType(ImageView.ScaleType.FIT_XY);
					imageView.setBackgroundResource(R.drawable.video_icon);
					linearLayout.addView(imageView, relparams);
					map.put(taskQuestionBean.getTaskQuestion_ID(), previousAnswerBean.getAnswer());
					imageView.setOnLongClickListener(new VideoLongClickListener());
				}
			}
			Button button = new Button(this);
			button.setBackgroundResource(R.drawable.video);
			if (null != previousAnswerBean
					&& previousAnswerBean.getTaskQuestion_ID().equals(taskQuestionBean.getTaskQuestion_ID())) {
				if (null != previousAnswerBean.getAnswer() && !"".equals(previousAnswerBean.getAnswer())) {
					button.setVisibility(View.GONE);
				} else {
					button.setVisibility(View.VISIBLE);
				}

			}
			linearLayout.addView(button);
			button.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// Intent recordintent = new
					// Intent(MediaStore.ACTION_VIDEO_CAPTURE);
					// recordintent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
					// startActivityForResult(recordintent, REQUEST_CODE_VIDEO);
					MyDialog.Builder builder = new MyDialog.Builder(AnswerQuestionActivity.this);
					builder.setTitle("选择录像来源")
							.setPositiveButton("本地", new android.content.DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									Intent picture = new Intent(Intent.ACTION_PICK,
											android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
									startActivityForResult(picture, REQUEST_CODE_VIDEO);
									dialog.dismiss();
								}
							}).setNegativeButton("实时", new android.content.DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									Intent recordintent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
									recordintent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
									recordintent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 300);
									startActivityForResult(recordintent, REQUEST_CODE_VIDEO);
									dialog.dismiss();
								}
							});
					Dialog dialog = builder.create();
					dialog.show();
				}
			});
		} else if ("6".equals(qtype)) { // 动态创建文本框
			linearLayout.setOrientation(LinearLayout.HORIZONTAL);
			final EditText editText = new EditText(this);

			if (questionStr.indexOf("数") != -1) {
				editText.setInputType(InputType.TYPE_CLASS_NUMBER);
			} else {

				editText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
			}
			editText.setGravity(Gravity.TOP);
			// 改变默认的单行模式
			editText.setSingleLine(false);
			// 水平滚动设置为False
			editText.setHorizontallyScrolling(false);
			editText.setMinLines(4);
			// editText.setMaxLines(1);
			if (null != previousAnswerBean
					&& previousAnswerBean.getTaskQuestion_ID().equals(taskQuestionBean.getTaskQuestion_ID())) {
				editText.setText(previousAnswerBean.getAnswer());
				map.put(taskQuestionBean.getTaskQuestion_ID(), previousAnswerBean.getAnswer());
			}
			editText.setLayoutParams(params);
			linearLayout.addView(editText);
			editText.addTextChangedListener(new TextWatcher() {
				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					// if(count>0){

					map.put(taskQuestionBean.getTaskQuestion_ID(), s.toString());
					// }
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {

					map.put(taskQuestionBean.getTaskQuestion_ID(), s.toString());
				}

				@Override
				public void afterTextChanged(Editable s) {
					//
					// map.put(nurseItem.getName(), s.toString());
				}
			});
		}
	}

	// 点击图片
	class ItemClickListener implements OnItemClickListener {
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			Log.i("TAG", "shixianlezhegefangfa");
			// 在本例中arg2=arg3
			HashMap<String, Object> item = (HashMap<String, Object>) arg0.getItemAtPosition(arg2);
			// 显示所选Item的ItemText
			if (!"button".equals((String) item.get("ItemText"))) {
				Intent intent = new Intent(AnswerQuestionActivity.this, FullscreenShowActivity.class);
				intent.putExtra("images", (String) item.get("ItemText"));
				intent.putExtra("type", "0");
				AnswerQuestionActivity.this.startActivity(intent);
			} else {
				if ("0".equals(PhotoMode)) {
					MyDialog.Builder builder = new MyDialog.Builder(AnswerQuestionActivity.this);
					builder.setTitle("请选择照片来源")
							.setPositiveButton("相册", new android.content.DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									Intent picture = new Intent(Intent.ACTION_PICK,
											android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
									startActivityForResult(picture, REQUEST_CODE_PICK_IMAGE);
									dialog.dismiss();
								}
							}).setNegativeButton("相机", new android.content.DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									Intent intent = new Intent(AnswerQuestionActivity.this, UseCameraActivity.class);
									startActivityForResult(intent, REQUEST_CODE_CAPTURE_CAMEIA);
									dialog.dismiss();
								}
							});
					Dialog dialog = builder.create();
					dialog.show();
				} else {
					String state = Environment.getExternalStorageState();
					if (state.equals(Environment.MEDIA_MOUNTED)) {
						Intent intent = new Intent(AnswerQuestionActivity.this, UseCameraActivity.class);
						startActivityForResult(intent, REQUEST_CODE_CAPTURE_CAMEIA);

					} else {
						Toast.makeText(AnswerQuestionActivity.this, "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
					}

				}
			}
		}
	}

	// 长按图片
	class ImageLongClickListener implements OnItemLongClickListener {

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			final HashMap<String, Object> item = (HashMap<String, Object>) arg0.getItemAtPosition(arg2);
			if (!"button".equals((String) item.get("ItemText"))) {
				gridView.setOnItemClickListener(null);
				MyDialog.Builder builder = new MyDialog.Builder(AnswerQuestionActivity.this);
				builder.setTitle("确定要删除吗？")
						.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								// Toast.makeText(AnswerQuestionActivity.this,
								// "1111", Toast.LENGTH_LONG).show();
								// gridView.setOnItemClickListener(new
								// ItemClickListener());
								if (null != lstImageItem && lstImageItem.size() > 0) {
									removeImg(item);
									gridView.setOnItemClickListener(new ItemClickListener());
								}
							}
						}).setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								gridView.setOnItemClickListener(new ItemClickListener());
							}
						});
				Dialog dialog = builder.create();
				dialog.show();
			}
			return false;
		}
	}

	class AudioLongClickListener implements OnLongClickListener {

		@Override
		public boolean onLongClick(View arg0) {
			MyDialog.Builder builder = new MyDialog.Builder(AnswerQuestionActivity.this);
			builder.setTitle("确定要删除吗？").setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					linearLayout.removeAllViews();
					map.remove(taskQuestionBean.getTaskQuestion_ID());
					button = new Button(AnswerQuestionActivity.this);
					button.setBackgroundResource(R.drawable.audio);
					linearLayout.addView(button);
					button.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							MyDialog.Builder builder = new MyDialog.Builder(AnswerQuestionActivity.this);
							builder.setTitle("选择录音来源")
									.setPositiveButton("本地", new android.content.DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											Intent picture = new Intent(Intent.ACTION_PICK,
													android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
											startActivityForResult(picture, REQUEST_CODE_AUDIO);
											dialog.dismiss();
										}
									}).setNegativeButton("实时", new android.content.DialogInterface.OnClickListener() {

										@Override
										public void onClick(DialogInterface dialog, int which) {
											Intent audiorecord = new Intent(AnswerQuestionActivity.this,
													AudioRecord.class);
											startActivityForResult(audiorecord, REQUEST_CODE_AUDIO);
											dialog.dismiss();
										}
									});
							Dialog dialog = builder.create();
							dialog.show();
						}
					});
				}
			}).setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					gridView.setOnItemClickListener(new ItemClickListener());
				}
			});
			Dialog dialog = builder.create();
			dialog.show();
			return false;
		}
	}

	class VideoLongClickListener implements OnLongClickListener {
		@Override
		public boolean onLongClick(View arg0) {
			MyDialog.Builder builder = new MyDialog.Builder(AnswerQuestionActivity.this);
			builder.setTitle("确定要删除吗？").setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					linearLayout.removeAllViews();
					map.remove(taskQuestionBean.getTaskQuestion_ID());
					Button button = new Button(AnswerQuestionActivity.this);
					button.setBackgroundResource(R.drawable.video);
					linearLayout.addView(button);
					button.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							// Intent recordintent = new
							// Intent(MediaStore.ACTION_VIDEO_CAPTURE);
							// recordintent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,
							// 1);
							// startActivityForResult(recordintent,
							// REQUEST_CODE_VIDEO);
							MyDialog.Builder builder = new MyDialog.Builder(AnswerQuestionActivity.this);
							builder.setTitle("选择录像来源")
									.setPositiveButton("本地", new android.content.DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											Intent picture = new Intent(Intent.ACTION_PICK,
													android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
											startActivityForResult(picture, REQUEST_CODE_VIDEO);
											dialog.dismiss();
										}
									}).setNegativeButton("实时", new android.content.DialogInterface.OnClickListener() {

										@Override
										public void onClick(DialogInterface dialog, int which) {
											Intent recordintent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
											recordintent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
											recordintent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 300);
											startActivityForResult(recordintent, REQUEST_CODE_VIDEO);
											dialog.dismiss();
										}
									});
							Dialog dialog = builder.create();
							dialog.show();
						}
					});
				}
			}).setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					gridView.setOnItemClickListener(new ItemClickListener());
				}
			});
			Dialog dialog = builder.create();
			dialog.show();
			return false;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		// 图片返回
		if (requestCode == REQUEST_CODE_PICK_IMAGE && null != data) {
			if (null != data.getData()) {
				Uri selectedImage = data.getData();
				String[] filePathColumns = { MediaStore.Images.Media.DATA };
				Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null, null, null);
				if (null != c) {
					c.moveToFirst();
					int columnIndex = c.getColumnIndex(filePathColumns[0]);
					String picturePath = c.getString(columnIndex);
					// 获取图片并显示
					getBitmap(picturePath);
					c.close();
				}
			}
		}
		if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA && null != data) {

			if (null != data.getStringExtra(UseCameraActivity.IMAGE_PATH)) {
				String path = data.getStringExtra(UseCameraActivity.IMAGE_PATH);
				savePictureSelf(path);
				getBitmap(path);
			} else {
				Toast.makeText(this, "无法获取拍摄后文件", Toast.LENGTH_LONG).show();
			}
		}
		if (requestCode == REQUEST_CODE_AUDIO && null != data) {
			// Uri uri = data.getData();
			if (null != data.getStringExtra("uri")) {
				map.put(taskQuestionBean.getTaskQuestion_ID(), data.getStringExtra("uri"));

			} else {
				Uri selected = data.getData();
				String[] filePathColumns = { MediaStore.Audio.Media.DATA };
				Cursor c = this.getContentResolver().query(selected, filePathColumns, null, null, null);
				if (null != c) {
					c.moveToFirst();
					int columnIndex = c.getColumnIndex(filePathColumns[0]);
					String Path = c.getString(columnIndex);
					c.close();
					map.put(taskQuestionBean.getTaskQuestion_ID(), Path);
				}
			}

			if (null != map.get(taskQuestionBean.getTaskQuestion_ID())) {
				linearLayout.removeAllViews();
				Display mDisplay = getWindowManager().getDefaultDisplay();
				int W = mDisplay.getWidth();
				Log.v("qqqq", W + "");
				RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(W / 4, W / 4);
				// 根据照片的位置获取图片
				linearLayout.setOrientation(LinearLayout.HORIZONTAL);
				ImageView imageView = new ImageView(this);
				params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
				// imageView.setLayoutParams(params);
				imageView.setPadding(20, 0, 20, 0);
				imageView.setScaleType(ImageView.ScaleType.FIT_XY);
				imageView.setBackgroundResource(R.drawable.audio_icon);
				linearLayout.addView(imageView, params);
				imageView.setOnLongClickListener(new AudioLongClickListener());

			}
		}
		if (requestCode == REQUEST_CODE_VIDEO && null != data) {
			if (null != data.getData()) {
				Uri uri = data.getData();
				Log.v("qqqq", uri + "");
				if (uri.getPath().indexOf(".tmp") >= 0) {
					uri = Uri.parse(uri.getPath().replace(".tmp", ""));
				}
				String strVideoPath = "";
				if ("file".equals(uri.getScheme())) {
					strVideoPath = uri.getEncodedPath();
				} else if ("content".equals(uri.getScheme())) {
					Cursor cursor = this.getContentResolver().query(uri, null, null, null, null);
					if (cursor.moveToNext()) {
						/** _data：文件的绝对路径 ，_display_name：文件名 */
						strVideoPath = cursor.getString(cursor.getColumnIndex("_data"));
					}
				}
				File file = new File(strVideoPath);
				if (file.exists() && file.length() > 20000000) {
					Toast.makeText(AnswerQuestionActivity.this, "文件太大，超出要求", Toast.LENGTH_LONG).show();
					return;
				}
				map.put(taskQuestionBean.getTaskQuestion_ID(), strVideoPath);
			} else {
				Toast.makeText(this, "视频拍摄时间太短，无法保存", Toast.LENGTH_LONG).show();
			}

			if (null != map.get(taskQuestionBean.getTaskQuestion_ID())) {
				linearLayout.removeAllViews();
				Display mDisplay = getWindowManager().getDefaultDisplay();
				int W = mDisplay.getWidth();
				Log.v("qqqq", W + "");
				RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(W / 4, W / 4);
				// 根据照片的位置获取图片
				linearLayout.setOrientation(LinearLayout.HORIZONTAL);
				ImageView imageView = new ImageView(this);
				params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
				// imageView.setLayoutParams(params);
				imageView.setPadding(20, 0, 20, 0);
				imageView.setScaleType(ImageView.ScaleType.FIT_XY);
				imageView.setBackgroundResource(R.drawable.video_icon);
				linearLayout.addView(imageView, params);
				imageView.setOnLongClickListener(new VideoLongClickListener());
			}
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putSerializable("taskQuestionBean", taskQuestionBean);

		Bundle mapBundle = new Bundle();
		Set<String> keySet = map.keySet();
		Iterator<String> iter = keySet.iterator();
		while (iter.hasNext()) {
			String key = iter.next();
			mapBundle.putString(key, String.valueOf(map.get(key)));
		}
		outState.putBundle("map", mapBundle);

		outState.putSerializable("taskBean", taskBean);

		outState.putSerializable("list", lstImageItem);

		outState.putString("PhotoMode", PhotoMode);
		outState.putInt("PhotoNum", PhotoNum);

		super.onSaveInstanceState(outState);
	}

	void showImg(String path) {
		Log.e("showImg", path);

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT);
		linearLayout.removeAllViews();
		linearLayout.setLayoutParams(params);
		gridView.setNumColumns(4);
		gridView.setVerticalSpacing(20);
		gridView.setLayoutParams(params);
		if (null != lstImageItem && lstImageItem.size() > 0) {
			if (count == 0) {
				lstImageItem.remove(0);
			} else {
				lstImageItem.remove(count);
			}
		}
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("ItemImage", path);
		hashMap.put("ItemText", path);
		lstImageItem.add(hashMap);
		count++;
		if (count == PhotoNum) {
			// button.setVisibility(View.GONE);
		} else {
			HashMap<String, Object> pathHashMap = new HashMap<String, Object>();
			pathHashMap.put("ItemImage", R.drawable.camera);
			pathHashMap.put("ItemText", "button");
			lstImageItem.add(pathHashMap);
		}
		SimpleAdapter saImageItems = new SimpleAdapter(this, // 没什么解释
				lstImageItem, // 数据来源
				R.layout.night_item, // night_item的XML实现
				// 动态数组与ImageItem对应的子项
				new String[] { "ItemImage", "ItemText" }, new int[] { R.id.ItemImage, R.id.ItemText });
		gridView.setAdapter(saImageItems);
		gridView.setOnItemClickListener(new ItemClickListener());
		gridView.setOnItemLongClickListener(new ImageLongClickListener());
		linearLayout.addView(gridView);
		saImageItems.notifyDataSetChanged();

		if (null == imgtemp || "null".equals(imgtemp)) {
			imgtemp = "";
		}
		imgtemp += ("#" + path);
		if (imgtemp.length() > 0) {
			if (imgtemp.substring(0, 1).equals("#")) {
				imgtemp = imgtemp.substring(1);
			}
		}
		map.put(taskQuestionBean.getTaskQuestion_ID(), imgtemp);
	}

	void removeImg(HashMap<String, Object> pathHashMap) {
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT);
		linearLayout.removeAllViews();
		linearLayout.setLayoutParams(params);
		gridView.setNumColumns(4);
		gridView.setVerticalSpacing(20);
		gridView.setLayoutParams(params);
		if (null != lstImageItem && lstImageItem.size() > 0) {
			lstImageItem.remove(pathHashMap);
		}

		count--;
		Log.v("qqqq", count + "");
		if (null != lstImageItem && lstImageItem.size() > 0) {
			if (count == 0) {
				lstImageItem.remove(0);
			} else {
				HashMap<String, Object> hashMap = lstImageItem.get(lstImageItem.size() - 1);
				if ("button".equals(hashMap.get("ItemText").toString())) {
					lstImageItem.remove(lstImageItem.size() - 1);
				}
			}
		}
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("ItemImage", R.drawable.camera);
		hashMap.put("ItemText", "button");
		lstImageItem.add(hashMap);
		SimpleAdapter saImageItems = new SimpleAdapter(this, // 没什么解释
				lstImageItem, // 数据来源
				R.layout.night_item, // night_item的XML实现
				// 动态数组与ImageItem对应的子项
				new String[] { "ItemImage", "ItemText" }, new int[] { R.id.ItemImage, R.id.ItemText });
		gridView.setAdapter(saImageItems);
		saImageItems.notifyDataSetChanged();
		gridView.setOnItemClickListener(new ItemClickListener());
		gridView.setOnItemLongClickListener(new ImageLongClickListener());
		linearLayout.addView(gridView);
		imgtemp = "";
		for (int i = 0; i < lstImageItem.size(); i++) {
			HashMap<String, Object> map = lstImageItem.get(i);
			if (!"button".equals(map.get("ItemText").toString())) {
				imgtemp += ("#" + map.get("ItemImage"));
			}
		}

		if (imgtemp.length() > 0) {
			if (imgtemp.substring(0, 1).equals("#")) {
				imgtemp = imgtemp.substring(1);
			}
		}
		Log.v("qqqq", imgtemp);
		map.put(taskQuestionBean.getTaskQuestion_ID(), imgtemp);
	}

	private Uri getImageUri(String path) {

		return Uri.fromFile(new File(path));
	}

	private Bitmap getBitmap(String path) {
		Log.e("PATH", path);
		Uri uri = getImageUri(path);
		InputStream in = null;
		try {
			in = mContentResolver.openInputStream(uri);

			// Decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;

			BitmapFactory.decodeStream(in, null, o);
			in.close();

			int scale = 1;
			if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
				scale = (int) Math.pow(2, (int) Math
						.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
			}

			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			in = mContentResolver.openInputStream(uri);
			Bitmap b = BitmapFactory.decodeStream(in, null, o2);
			String outPath = S.getPath(path);
			if (null != b) {
				if (null != taskBean && !"".equals(taskBean.getPhotoCompression())) {
					Log.e("getBitmap", taskBean.getPhotoCompression());
					if ("1".equals(taskBean.getPhotoCompression())) {
						b = comp(b, 1280f, 720f, outPath);
					} else if ("2".equals(taskBean.getPhotoCompression())) {
						b = comp(b, 1920f, 1080f, outPath);
					} else {
						b = comp(b, 3000f, 2000f, outPath);
					}
				} else {
					b = comp(b, 3000f, 2000f, outPath);
				}
				showImg(outPath);
			} else {
				Toast.makeText(AnswerQuestionActivity.this, "图片或照片已损坏", Toast.LENGTH_LONG).show();
			}

			in.close();

			return b;
		} catch (Exception e) {
			Log.v("qqqq", e.getMessage());
		}
		return null;
	}

	// 压缩图片分辨率
	private Bitmap comp(Bitmap image, float hh, float ww, String path) {
		hh = hh + 200;// 给一定的富裕防止图片被缩过小
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		if (baos.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 这里压缩50%，把压缩后的数据存放到baos中
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		// float hh = 800f;//这里设置高度为800f
		// float ww = 480f;//这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		// int be = 1;// be=1表示不缩放
		// if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
		// be = (int) (newOpts.outWidth / ww);
		// } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
		// be = (int) (newOpts.outHeight / hh);
		// }
		int be = 1;// be=1表示不缩放
		if (w > hh || h > hh) {
			be = 2;
			while (w / be > hh || h / be > hh) {
				be = be + 2;
			}
		}
		newOpts.inSampleSize = be;// 设置缩放比例
		newOpts.inJustDecodeBounds = false;
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		isBm = new ByteArrayInputStream(baos.toByteArray());
		bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		return compressImage(bitmap, path);// 压缩好比例大小后再进行质量压缩
	}

	// 图片质量压缩
	private Bitmap compressImage(Bitmap image, String path) {
		// ByteArrayOutputStream baos = new ByteArrayOutputStream();
		// image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//
		// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		// int options = 100;
		// while (baos.toByteArray().length / 1024 > 300) { //
		// 循环判断如果压缩后图片是否大于100kb,大于继续压缩
		// baos.reset();// 重置baos即清空baos
		// image.compress(Bitmap.CompressFormat.JPEG, options, baos);//
		// 这里压缩options%，把压缩后的数据存放到baos中
		// options -= 10;// 每次都减少10
		// }
		// ByteArrayInputStream isBm = new
		// ByteArrayInputStream(baos.toByteArray());//
		// 把压缩后的数据baos存放到ByteArrayInputStream中
		// Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//
		// 把ByteArrayInputStream数据生成图片

		File f = new File(path);
		if (f.exists()) {
			f.delete();
		}
		try {
			FileOutputStream out = new FileOutputStream(f);
			image.compress(Bitmap.CompressFormat.JPEG, 90, out);
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return image;
	}

	@Override
	protected void onResume() {
		if (null != taskBean && null != taskQuestionBean) {
			if ("1".equals(taskBean.getGoBackSet()) && !"1".equals(taskQuestionBean.getOrderIndex())) {
				btnPrevious.setVisibility(View.VISIBLE);
			} else {
				btnPrevious.setVisibility(View.GONE);
			}
		}
		init();
		super.onResume();
	}

	private String getSPString() {
		SharedPreferences sp = this.getSharedPreferences("login", Context.MODE_PRIVATE);
		return sp.getString("UserMobile", "");
	}

	private void isFirstAnswer() {
		QuestionAnswerDao answerdao = new QuestionAnswerDao(this);
		ArrayList<QuestionAnswerBean> arrayList = answerdao.query(taskid);
		if (arrayList.size() == 0) {
			isFirstDo = true;
		}
	}

	private void changeTaskFirstModifyTime() {
		String data = com.socool.sinofaith.util.DateUtils.getStringDate();
		SifTaskDao dao = new SifTaskDao(this);
		ArrayList<SifTaskBean> arrayList = dao.query(taskid);
		for (SifTaskBean bean : arrayList) {
			bean.setModifyTime(data);
			dao.update(bean);
		}

	}
}
